package GUILayer;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import ControlLayer.ProductCtr;
import ControlLayer.SupplierCtr;
import ModelLayer.Product;
import ModelLayer.Supplier;

public class SupplierMenu
{
	private static SupplierMenu instance=null;
	
	public JFrame frmSupplierInformation;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JTextField textField_4;
	private JTextField textField_5;
	private JTable table;
	private JScrollPane scrollPane;

	public SupplierMenu()
	{
		initialize();
		frmSupplierInformation.setVisible(true);		
	}
	
	public static SupplierMenu getInstance()
	{
		if(instance==null)
		{
			instance=new SupplierMenu();
		}
		return instance;
	}
	
	public void initialize()
	{
		frmSupplierInformation = new JFrame();
		frmSupplierInformation.setTitle("Supplier information");
		frmSupplierInformation.setBounds(100, 100, 900, 500);
		frmSupplierInformation.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmSupplierInformation.getContentPane().setLayout(null);
		frmSupplierInformation.setUndecorated(true);
		frmSupplierInformation.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Supplier data", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(10, 7, 735, 120);
		frmSupplierInformation.getContentPane().add(panel_1);
		panel_1.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("Supplier ID:");
		lblNewLabel.setBounds(6, 16, 100, 25);
		panel_1.add(lblNewLabel);
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(6, 52, 100, 25);
		panel_1.add(lblName);
		lblName.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JLabel lblAddress = new JLabel("Address:");
		lblAddress.setBounds(6, 88, 100, 25);
		panel_1.add(lblAddress);
		lblAddress.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JLabel lblCountry = new JLabel("Country:");
		lblCountry.setBounds(375, 16, 100, 25);
		panel_1.add(lblCountry);
		lblCountry.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JLabel lblPhoneNumber = new JLabel("Phone number:");
		lblPhoneNumber.setBounds(375, 52, 100, 25);
		panel_1.add(lblPhoneNumber);
		lblPhoneNumber.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JLabel lblEmail = new JLabel("E-Mail:");
		lblEmail.setBounds(375, 88, 100, 25);
		panel_1.add(lblEmail);
		lblEmail.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		textField = new JTextField();
		textField.setBounds(96, 20, 240, 20);
		panel_1.add(textField);
		textField.setColumns(10);
		
		textField_1 = new JTextField();
		textField_1.setBounds(96, 56, 240, 20);
		panel_1.add(textField_1);
		textField_1.setColumns(10);
		
		textField_2 = new JTextField();
		textField_2.setBounds(96, 92, 240, 20);
		panel_1.add(textField_2);
		textField_2.setColumns(10);
		
		textField_3 = new JTextField();
		textField_3.setBounds(485, 20, 240, 20);
		panel_1.add(textField_3);
		textField_3.setColumns(10);
		
		textField_4 = new JTextField();
		textField_4.setBounds(485, 56, 240, 20);
		panel_1.add(textField_4);
		textField_4.setColumns(10);
		
		textField_5 = new JTextField();
		textField_5.setBounds(485, 92, 240, 20);
		panel_1.add(textField_5);
		textField_5.setColumns(10);
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "Options", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setBounds(10, 142, 125, 338);
		frmSupplierInformation.getContentPane().add(panel);
		panel.setLayout(null);
		
		//search button
		JButton btnNewButton = new JButton("Search");
		btnNewButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0)
			{
				SupplierCtr supplierCtr=new SupplierCtr();
				
				if(textField.getText().equals("")!=true)
				{
					String stringID=textField.getText();
					System.out.println(stringID);
					int id=Integer.parseInt(stringID);
					Supplier supplier = supplierCtr.getSuppById(id);
					putValuesOnTheScreen(supplier);
					
					DefaultTableModel tdm=(DefaultTableModel)table.getModel();
					tdm.getDataVector().removeAllElements();
					tdm.fireTableDataChanged();
				}
				else
				{
					if(textField_1.getText().equals("")!=true)
					{
						String name=textField_1.getText();
						System.out.println(name);
						Supplier supplier=supplierCtr.getSupplierByName(name);
						putValuesOnTheScreen(supplier);
						
						DefaultTableModel tdm=(DefaultTableModel)table.getModel();
						tdm.getDataVector().removeAllElements();
						tdm.fireTableDataChanged();
					}
					else
					{
						JOptionPane.showMessageDialog(null, "Please insert either id or name for the supplier.", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
				
				DefaultTableModel tdm=(DefaultTableModel)table.getModel();
				tdm.getDataVector().removeAllElements();
				tdm.fireTableDataChanged();
			}
		});
		btnNewButton.setBounds(6, 16, 110, 35);
		panel.add(btnNewButton);
		
		//update supplier button
		JButton btnUpdate = new JButton("Update");
		btnUpdate.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				SupplierCtr supplierCtr=new SupplierCtr();
				
				if(textField.getText().equals("")!=true)
				{
					String stringID=textField.getText();
					int suppId=Integer.parseInt(stringID);
					
					Supplier supplier1=supplierCtr.getSuppById(suppId);
					if(checkSupplierExistence(supplier1)==true)
					{
						if(textField_1.getText().equals("")!=true || 
							textField_2.getText().equals("")!=true ||
							textField_3.getText().equals("")!=true ||
							textField_4.getText().equals("")!=true ||
							textField_5.getText().equals("")!=true)
						{
							String suppName=textField_1.getText();
							String suppAddress=textField_2.getText();
							String suppCountry=textField_3.getText();
							String suppPhoneNo=textField_4.getText();
							String suppEmail=textField_5.getText();
							
							supplierCtr.updateSupplierByID(suppId, suppName, suppAddress, suppCountry, suppPhoneNo, suppEmail);
							
							clearValues();
							
							JOptionPane.showMessageDialog(null, "Supplier has been successfully updated.", "Information", JOptionPane.INFORMATION_MESSAGE);
						}
						else
						{
							JOptionPane.showMessageDialog(null, "Some fields may be empty!", "Error!", JOptionPane.ERROR_MESSAGE);
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "There is no such supplier!", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
				else
				{
					if(textField_1.getText().equals("")!=true)
					{
						String suppName=textField_1.getText();
						Supplier supplier2=supplierCtr.getSupplierByName(suppName);
						if(checkSupplierExistence(supplier2)==true)
						{
							if(textField_1.getText().equals("")!=true || textField_2.getText().equals("")!=true || textField_3.getText().equals("")!=true || textField_4.getText().equals("")!=true || textField_5.getText().equals("")!=true)
							{
								int suppID=supplier2.getId();
								String suppAddress=textField_2.getText();
								String suppCountry=textField_3.getText();
								String suppPhoneNo=textField_4.getText();
								String suppEmail=textField_5.getText();
								
								supplierCtr.updateSupplierByID(suppID, suppName, suppAddress, suppCountry, suppPhoneNo, suppEmail);
								
								clearValues();
								
								JOptionPane.showMessageDialog(null, "Supplier has been successfully updated.", "Information", JOptionPane.INFORMATION_MESSAGE);
							}
							else
							{
								JOptionPane.showMessageDialog(null, "Some fields may be empty!", "Error!", JOptionPane.ERROR_MESSAGE);
							}
						}
						else
						{
							JOptionPane.showMessageDialog(null, "There is no such supplier!", "Error!", JOptionPane.ERROR_MESSAGE);
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "Please insert either id or name for the supplier.", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
				
				DefaultTableModel tdm=(DefaultTableModel)table.getModel();
				tdm.getDataVector().removeAllElements();
				tdm.fireTableDataChanged();
			}
		});
		btnUpdate.setBounds(6, 108, 110, 35);
		panel.add(btnUpdate);
		
		//delete supplier button
		JButton btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				SupplierCtr supplierCtr=new SupplierCtr();
				
				if(textField.getText().equals("")!=true)
				{
					String stringID=textField.getText();
					int suppId=Integer.parseInt(stringID);
					
					Supplier supplier1=supplierCtr.getSuppById(suppId);
					if(checkSupplierExistence(supplier1)==true)
					{
						supplierCtr.deleteSupplierByID(suppId);
						
						clearValues();
						
						JOptionPane.showMessageDialog(null, "Supplier has been deleted from the system.", "Information", JOptionPane.INFORMATION_MESSAGE);
					}
					else
					{
						JOptionPane.showMessageDialog(null, "There is no such supplier!", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
				else
				{
					if(textField_1.getText().equals("")!=true)
					{
						String suppName=textField_1.getText();
						Supplier supplier2=supplierCtr.getSupplierByName(suppName);
						if(checkSupplierExistence(supplier2)==true)	
						{
							supplierCtr.deleteSupplierByName(suppName);
							
							clearValues();
							
							JOptionPane.showMessageDialog(null, "Supplier has been deleted from the system.", "Information", JOptionPane.INFORMATION_MESSAGE);
						}
						else
						{
							JOptionPane.showMessageDialog(null, "There is no such supplier!", "Error!", JOptionPane.ERROR_MESSAGE);
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "Please insert either id or name for the supplier.", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
				
				
			}
		});
		btnDelete.setBounds(6, 154, 110, 35);
		panel.add(btnDelete);
		
		//get products for a supplier id
		JButton btnGetProducts = new JButton("Get products");
		btnGetProducts.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				SupplierCtr suppCtr=new SupplierCtr();
				
				if(textField.getText().equals("")==true)
				{
					JOptionPane.showMessageDialog(null, "Please insert id of the supplier.", "Error!", JOptionPane.ERROR_MESSAGE);
				}
				else
				{
					String stringID=textField.getText();
					int suppId=Integer.parseInt(stringID);
					Supplier supplier1=suppCtr.getSuppById(suppId);
					putValuesOnTheScreen(supplier1);
					if(textField_1.getText().equals("")!=true)
					{
						ProductCtr prodCtr=new ProductCtr();
						ArrayList<Product> suppProdList=new ArrayList<Product>();
						suppProdList=prodCtr.getAllSuppProd(suppId);
						
						DefaultTableModel model2 = new DefaultTableModel()
						{
							private static final long serialVersionUID = 1L;

							@Override
							public boolean isCellEditable(int row, int column)
							{
								//all cells false
								return false;
							}
						};
					
						//DefaultTableModel model2 = new DefaultTableModel();
						model2.setColumnIdentifiers(new String[] {"ProdID", "Name", "PurchasePrice", "SalesPrice", "RentPrice", "CountryOfOrigin", "MinStock"});
					
						try
						{
							for(Product productObj : suppProdList)
							{
								model2.addRow(new String[]
									{
									String.valueOf(productObj.getId()),
									productObj.getName(),
									String.valueOf(productObj.getPurchasePrice()),
									String.valueOf(productObj.getSalesPrice()),
									String.valueOf(productObj.getRentPrice()),
									productObj.getCountry(),
									String.valueOf(productObj.getMinStock())
									});
							}
							table.setModel(model2);
						}
					
						catch(Exception e)
						{
							System.out.println("Exception: " + e);
						}
					}
					else
					{
						JOptionPane.showMessageDialog(null, "There is no such supplier!", "Error!", JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});
		btnGetProducts.setBounds(6, 246, 110, 35);
		panel.add(btnGetProducts);
		
		//insert button
		JButton btnInsert = new JButton("Insert");
		btnInsert.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				if(textField_1.getText().equals("")==true || textField_2.getText().equals("")==true || textField_3.getText().equals("")==true || textField_4.getText().equals("")==true || textField_5.getText().equals("")==true)
				{
					JOptionPane.showMessageDialog(null, "Please insert all data!", "Error!", JOptionPane.ERROR_MESSAGE);
				}
				else
				{
					SupplierCtr suppCtr=new SupplierCtr();
					String suppName=textField_1.getText();
					String suppAddress=textField_2.getText();
					String suppCountry=textField_3.getText();
					String suppPhoneNo=textField_4.getText();
					String suppEmail=textField_5.getText();
					
					suppCtr.inserNewSupplier(suppName, suppAddress, suppCountry, suppPhoneNo, suppEmail);
					
					DefaultTableModel tdm=(DefaultTableModel)table.getModel();
					tdm.getDataVector().removeAllElements();
					tdm.fireTableDataChanged();
					
					JOptionPane.showMessageDialog(null, "Supplier has been inserted into the table.", "Information", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		btnInsert.setBounds(6, 62, 110, 35);
		panel.add(btnInsert);
		
		//clear window data button
		JButton btnClear = new JButton("Clear");
		btnClear.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				clearValues();
			}
		});
		btnClear.setBounds(6, 200, 110, 35);
		panel.add(btnClear);
		
		//get suppliers button
		JButton btnGetSuppliers = new JButton("Get suppliers");
		btnGetSuppliers.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				try
				{
					table.setModel(returnModel1());
				}				
				catch(Exception e)
				{
					System.out.println("Exception: " + e);
				}
			}
		});
		btnGetSuppliers.setBounds(6, 292, 110, 35);
		panel.add(btnGetSuppliers);
		
		//Minimize button
		JButton btnMinimise = new JButton("Minimize");
		btnMinimise.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				frmSupplierInformation.setState(JFrame.ICONIFIED);
			}
		});
		btnMinimise.setBounds(755, 65, 135, 47);
		frmSupplierInformation.getContentPane().add(btnMinimise);
		
		//close button
		JButton btnClose = new JButton("Close");
		btnClose.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				clearValues();
				frmSupplierInformation.dispose();
			}
		});
		btnClose.setBounds(755, 7, 135, 47);
		
		//scroll pane and table creation
		scrollPane = new JScrollPane();
		scrollPane.setBounds(146, 142, 744, 346);
		frmSupplierInformation.getContentPane().add(scrollPane);
		
		table = new JTable();
		scrollPane.setViewportView(table);
		frmSupplierInformation.getContentPane().add(btnClose);
		table.setFillsViewportHeight(true);
	}	
	
	public void putValuesOnTheScreen(Supplier suppObj)
	{
		textField.setText(String.valueOf(suppObj.getId()));
		textField_1.setText(suppObj.getName());
		textField_2.setText(suppObj.getAddress());
		textField_3.setText(suppObj.getCountry());
		textField_4.setText(suppObj.getPhoneNo());
		textField_5.setText(suppObj.getEmail());
	}
	
	public boolean checkSupplierExistence(Supplier suppObj)
	{
		boolean check=false;
				
		int id=suppObj.getId();
		String name=suppObj.getName();
		String address=suppObj.getAddress();
		String country=suppObj.getCountry();
		String phoneNo=suppObj.getPhoneNo();
		String email=suppObj.getEmail();
		
		String stringID=String.valueOf(id);
		
		if(stringID.equals("")==true || name.equals("")==true || address.equals("")==true ||
			country.equals("")==true || phoneNo.equals("")==true || email.equals("")==true)
		{
			check=false;
		}
		else
		{
			check=true;
		}
		return check;
	}
	
	public void clearValues()
	{
		textField.setText(null);
		textField_1.setText(null);
		textField_2.setText(null);
		textField_3.setText(null);
		textField_4.setText(null);
		textField_5.setText(null);
		
		DefaultTableModel tdm=(DefaultTableModel)table.getModel();
		tdm.getDataVector().removeAllElements();
		tdm.fireTableDataChanged();
	}
	
	private DefaultTableModel returnModel1()
	{
		DefaultTableModel model1 = new DefaultTableModel()
		{
			private static final long serialVersionUID = 1L;
			public boolean isCellEditable(int row, int column)
			{
				//all cells false
				return false;
			}
		};
		
		//table head
		model1.setColumnIdentifiers(new String[] {"SuppID", "Name", "Address", "Country", "PhoneNo", "E_Mail"});
		
		SupplierCtr suppCtr=new SupplierCtr();
		ArrayList<Supplier> suppList=new ArrayList<Supplier>();
		suppList=suppCtr.getAllSuppliers();
		
		//table values
		for(Supplier suppObj : suppList)
		{
			model1.addRow(new String[]
					{
					
					String.valueOf(suppObj.getId()),
					suppObj.getName(),
					suppObj.getAddress(),
					suppObj.getCountry(),
					suppObj.getPhoneNo(),
					suppObj.getEmail()
					
					});	
		}
		
		/*
		table.setCellSelectionEnabled(true);
		ListSelectionModel cellSelectionModel = table.getSelectionModel();
	    cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);	    
	    cellSelectionModel.addListSelectionListener(new ListSelectionListener() 
	    {
	    	@Override
	    	public void valueChanged(ListSelectionEvent e)
	    	{
	    		IFDBSupplier dbSupplier=new DBSupplier();
	    		Supplier supplier=new Supplier();
	    		
	    		int selectedRow = table.getSelectedRow();
	    		String selectedData = (String) table.getValueAt(selectedRow, 0);
	    		int id=Integer.parseInt(selectedData);
	    		
	    		supplier=dbSupplier.getSuppById(id, false);
	    		putValuesOnTheScreen(supplier);
	    	}
	    });
	    */
		
		return model1;
	}
}
